package com.falcon.web.security;

import cn.hutool.core.date.DateUtil;
import com.swan.security.cache.ITokenCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import java.util.Date;

/** Security Token 缓存实现
 * @author zongf
 * @date 2025-02-08
 **/
@Slf4j
@Component
public class SecurityTokenCache implements ITokenCache {

    @Autowired
    private CacheManager tokenCacheManager;

    private String tokenCacheName = "tokenCache";

    @Override
    public void set(String token, Object value){
        tokenCacheManager.getCache(tokenCacheName).put(token, value);
    }

    @Override
    public void remove(String token){
        Cache.ValueWrapper valueWrapper = tokenCacheManager.getCache(tokenCacheName).get(token);

        if (valueWrapper == null) {
            log.info("[清除token] token 不存在, token:{}", token);
        } else {
            tokenCacheManager.getCache(tokenCacheName).evict(token);

            Long createTime = (Long) valueWrapper.get();
            log.info("[清除token] 成功,createTime:{}, token:{}", token, DateUtil.formatTime(new Date(createTime)));
        }
    }

    @Override
    public Object get(String token){
        return tokenCacheManager.getCache(tokenCacheName).get(token);
    }

}
